package com.tulingxueyuan.mall.controller;


import com.tulingxueyuan.mall.common.api.CommonResult;
import com.tulingxueyuan.mall.common.util.ComConstants;
import com.tulingxueyuan.mall.common.util.JwtTokenUtil;
import com.tulingxueyuan.mall.modules.ums.model.UmsMember;
import com.tulingxueyuan.mall.modules.ums.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "UserController" ,description = "前台用户登录")
public class UserController {

    @Autowired
    UmsMemberService  memberService;
    @Autowired
    HttpSession  session;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;



    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsMember> register(@Validated @RequestBody UmsMember userMemberParam) {
        UmsMember umsMember = memberService.register(userMemberParam);
        if (umsMember == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(umsMember);
    }




    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@Validated  UmsMember userMemberParam) {
        UmsMember login = memberService.login(userMemberParam.getUsername(), userMemberParam.getPassword());
        if (login == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }

        session.setAttribute(ComConstants.FLAG_MEMBER_USER,login);
        //jwt
        String token = jwtTokenUtil.generateUserNameStr(login.getUsername());

        Map<String, String> tokenMap = new HashMap<>();
        // jwt
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("tokenHeader", tokenHeader);
        return CommonResult.success(tokenMap);
    }

}
